#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/20 15:23
# @Author  : Samge
"""
一键将所有 /resources/UI中的xxx.ui后缀文件转为python文件，
并将转换后的文件转移到目标目录下
"""
import os
from shutil import copyfile
from itkz.resources.utils.log import Log

UI_GOAL_DIR = '../'
UI_DIR = '../UI/'

QRC_GOAL_DIR = './'
QRC_DIR = '../'


def ui_to_py():
    """
    将ui文件转为py文件
    :return:
    """
    for path in os.listdir(UI_DIR):
        if not str(path).endswith('.ui'):
            continue
        os.chdir(UI_DIR)
        # xxx.ui -> xxx.py
        py_file = f"{UI_GOAL_DIR}{path.split('.')[0]}.py"
        Log().getlog().info(f"正在转换：{path} -> {py_file}")
        command = f"pyuic5 {path} -o {py_file}"
        os.system(command)

        # 读取转换后的py文件并替换依赖路径
        temp_txt = ''
        with open(py_file, "r", encoding='UTF-8') as f:
            temp_txt = f.read() or ''
            temp_txt = temp_txt.replace('import resources_rc', 'from itkz.resources import resources_rc')
            if 'policy_main.py' in py_file:
                # “在创建QCoreApplication实例之前，必须导入QtWebEngineWidgets”
                # 'QtWebEngineWidgets must be imported before a QCoreApplication instance is created'
                temp_txt = f"{temp_txt}\nfrom PyQt5 import QtWebEngineWidgets"
            f.close()
        with open(py_file, "w", encoding='UTF-8') as f:
            f.write(temp_txt)
            f.close()
    Log().getlog().info("全部ui文件转换完成")


def qrc_to_py():
    """
    将qrc文件转为py文件
    :return:
    """
    for path in os.listdir(QRC_DIR):
        if not str(path).endswith('.qrc'):
            continue
        os.chdir(QRC_DIR)
        # xxx.qrc -> xxx.py
        py_file = f"{QRC_GOAL_DIR}{path.split('.')[0]}_rc.py"
        Log().getlog().info(f"正在转换：{path} -> {py_file}")
        command = f"pyrcc5 {path} -o {py_file}"
        os.system(command)
    Log().getlog().info("全部qrc文件转换完成")


def cp_ui():
    """
    复制ui文件
    :return:
    """
    os.chdir(UI_DIR)
    source_ui_path = 'policy_source.ui'
    goal_ui_paths = [
        'policy_dtl_style.ui',
        'policy_files.ui',
        'policy_ignore.ui',
        'policy_source_rule.ui',
        'policy_table.ui',
        'policy_todo.ui',
    ]
    for path in goal_ui_paths:
        Log().getlog().info(f"正在复制：{source_ui_path} -> {path}")
        copyfile(source_ui_path, path)
    Log().getlog().info("复制完成")


if __name__ == '__main__':
    ui_to_py()
    qrc_to_py()
    # cp_ui()
